//
//  ZQHomeViewModel.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/17.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage
class ZQHomeViewModel: NSObject {

    //懒加载一个Viewmodel
     lazy  var  statusViewModel : [ZQstatusViewModel] = [ZQstatusViewModel]()
    
    
    func loadData (isPullup:Bool,finish:@escaping (Bool,Int) -> ()) {
        
        //https://api.weibo.com/2/statuses/home_timeline.json
//        let userUrl = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var maxId : Int64 = 0
        var sinceId : Int64 = 0
        
        if isPullup {
            maxId = statusViewModel.last?.status?.id ?? 0
            if maxId != 0 {
                maxId -= 1
            }
            }
            else{
                sinceId = statusViewModel.first?.status?.id ?? 0
                
            }
       
            
//        
//        let access_token = ["access_token" : ZQUserAccountViewModel.shared.access_token,
//                            "max_id" : "\(maxId)",
//                            "since_id" : "\(sinceId)"]
//            
            
            
//            使用HMStatusDAL来完成数据的请求
                        ZQStatusDAL.loadHomeData(sinceId: sinceId, maxId: maxId) { (array) in
                            //如果数组为空  请求失败
                            if array == nil {
                                finish(false, 0)
                                return
                            }
            
                            
                            var tempArray = [ZQstatusViewModel]()
                            //tempArray = NSArray.yy_modelArray(with: HMStatus.self, json: array) as! [HMStatus]
                            for item in array! {
                                let viewmodel = ZQstatusViewModel()
                                 let s = ZQStatus()
                                //调用对象的YYModel种扩充的对象方法传入字典 --> 模型数据
                                s.yy_modelSet(with: item)
                                //给viewmodel的status赋值
                                viewmodel.status = s
                                
                                //根据viewmodel来计算行高
                                //1. 根据viewmodel获取cell
                                let cell = self.loadCell(viewmodel: viewmodel)
                                //2.给cell的viewmodel赋值
                                cell.viewmodel = viewmodel
                                //3.强制提前刷新cell
                                cell.layoutIfNeeded()
                                //4.获取toolBar 最大Y值
                                viewmodel.rowHeight = cell.toolBar.frame.maxY
                                
                                //添加到一个临时数组中  获取数据都是按页一次获取20条数据
                                tempArray.append(viewmodel)
                            }
                            //执行成功的回调
                            //如果是上拉加载更多数据就应该执行追加的操作
                            if isPullup{
                                
                                self.statusViewModel = self.statusViewModel + tempArray
                            }else{
                                
                                
                                self.statusViewModel = tempArray +  self.statusViewModel
                            }
                            
                        
                            self.loadOnceImage(arr: tempArray, finished: finish)
                            
                            finish(true, tempArray.count)
                            
                            
            }
        }
    
        
//缓存单张图片
     private func loadOnceImage(arr : [ZQstatusViewModel] ,finished : @escaping (Bool,Int) -> ()) {
        
        if arr.count == 0{
            //返回结果
            finished(true,0)
            return
        }
        //使用调度组
        let group = DispatchGroup()
        //成功数组
        for viewmodel in arr {
            if viewmodel.imageUrls?.count == 1{
                let url = URL(string: viewmodel.imageUrls?.first?.wep360 ?? "")
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    
                    print("下载单张图片成功")
                    //入组
                  group.leave()
                })
                
            }
      
        }
        group.notify(queue: DispatchQueue.main, execute: {
        
            
            finished(true,arr.count)
        
        })
        

            }
      
         private func loadCell(viewmodel: ZQstatusViewModel) -> ZQstatusTableViewCell {
                    return (viewmodel.status?.retweeted_status == nil) ?  orginalCell : reweetedCell
                }
}
//HMNetworkTools.shared.request(method: .GET, urlString: userUrl, parameters: access_token) { (responseObject, error) in
//    if error != nil{
//        finish(false,0)
//        
//        return
//        
//    }
//    //成功后字典转模型  分析是数组嵌套
//    let dict = responseObject as! [String : Any]
//    //判断转换数组
//    guard let array = dict["statuses"] as? [[String : Any]]
//        
//        else {
//            finish(false,0)
//            //                    SVProgressHUD.showError(withStatus: ErrorTip)
//            return
//    }
//    
//    var timpArray = [ZQstatusViewModel]()
//    //拿到数组里面是字典,可以遍历字典,转型
//    for item in array {
//        //实例化Model
//        let viewModel = ZQstatusViewModel()
//        //在模型里可以用KVC给属性赋值
//        let s = ZQStatus()
//        
//        //下载了YYModel后可以实现YYModel的协议方法,
//        s.yy_modelSet(with: item)
//        
//        //给viewmode.status赋值
//        viewModel.status = s
//        
//        timpArray.append(viewModel)
//    }
//    //给属性赋值
//    
//    if isPullup{
//        
//        self.statusViewModel = self.statusViewModel + timpArray
//    }else{
//        
//        
//        self.statusViewModel = timpArray +  self.statusViewModel
//    }
//    
//    
//    
//    //
//    //            self.statusViewModel = timpArray
//    //回调
//    //            finish(true,timpArray.count)
//    
//    self.loadOnceImage(arr: timpArray, finished: finish)
//    
//    finish(true, timpArray.count)
//    
//}
//
//}
       
